﻿using Furion;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace furion.blog.Web.Core.Middleware
{
    /// <summary>
    /// 系统启动，停止监听
    /// </summary>
    public class LifetimeEventsHostedService : IHostedService
    {

        // 日志对象
        private readonly ILogger<LifetimeEventsHostedService> _logger;
        private readonly string appCode = App.Configuration["AppInfo:Code"];
        private readonly string appName = App.Configuration["AppInfo:Name"];
        private readonly IHostApplicationLifetime _appLifetime;

        public LifetimeEventsHostedService(IHostApplicationLifetime appLifetime,ILogger<LifetimeEventsHostedService> logger)
        {
            _appLifetime = appLifetime;
            _logger = logger;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _appLifetime.ApplicationStarted.Register(OnStarted);
            _appLifetime.ApplicationStopping.Register(OnStopping);
            _appLifetime.ApplicationStopped.Register(OnStopped);

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        private void OnStarted()
        {
            var interNetworkV6 = System.Net.Sockets.AddressFamily.InterNetworkV6;
            var interNetwork = System.Net.Sockets.AddressFamily.InterNetwork;
            var ipList = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
              .Select(p => p.GetIPProperties())
              .SelectMany(p => p.UnicastAddresses)
              .Where(p => (p.Address.AddressFamily == interNetwork || p.Address.AddressFamily == interNetworkV6) && !System.Net.IPAddress.IsLoopback(p.Address)).ToList();

            Console.WriteLine($"OnStarted has been called：【{appCode}】【{appName}】【{DateTime.Now}】 【{ipList[1].Address}】 【{ipList[0].Address}】");
            _logger.LogInformation($"OnStarted has been called：【{appCode}】【{appName}】【{DateTime.Now}】 【{ipList[1].Address}】 【{ipList[0].Address}】");
        }

        private void OnStopping()
        {
            Console.WriteLine($"OnStopping has been called：【{appCode}】【{appName}】【{DateTime.Now}】");
            _logger.LogInformation($"OnStopping has been called：【{appCode}】【{appName}】【{DateTime.Now}】");
        }

        private void OnStopped()
        {
            Console.WriteLine($"OnStopped has been called：【{appCode}】【{appName}】【{DateTime.Now}】");
            _logger.LogInformation($"OnStopped has been called：【{appCode}】【{appName}】【{DateTime.Now}】");
        }

    }
}
